//
//  QHUtil.swift
//  QHBinimageMan
//
//  Created by Anakin chen on 2021/3/16.
//

import Cocoa

class QHUtil: NSObject {
    
    // [Cocoa 怎样使NSImageView的图片正确的满屏放大缩小而没有黑边](https://blog.csdn.net/shagru/article/details/9779183)
    class func resizeImage(s_img: NSImage, size: NSSize) -> NSImage {
        let t_frame = NSMakeRect(0, 0, size.width, size.height)
        let t_img = NSImage(size: size)
        
        let s_size = s_img.size
        
        let ratioH = size.height / s_size.height
        let ratioW = size.width / s_size.width
        
        var cropRect = NSZeroRect
        
        if ratioH >= ratioW {
            cropRect.size.width = floor(size.width / ratioH)
            cropRect.size.height = s_size.height
        }
        else {
            cropRect.size.width = s_size.width
            cropRect.size.height = floor(size.height / ratioW)
        }
        
        cropRect.origin.x = floor((s_size.width - cropRect.size.width)/2)
        cropRect.origin.y = floor((s_size.height - cropRect.size.height)/2)
        
        t_img.lockFocus()
        
        s_img.draw(in: t_frame, from: cropRect, operation: .copy, fraction: 1.0, respectFlipped: true, hints: [NSImageRep.HintKey.interpolation: NSNumber(integerLiteral: Int(NSImageInterpolation.low.rawValue))])
        
        t_img.unlockFocus()
        
        return t_img
    }
    
    class func resizeImage2(s_img: NSImage, size: NSSize) -> NSImage {
        let t_img = NSImage(size: size)
        
        let s_size = s_img.size
        
        let ratioH = size.height / s_size.height
        let ratioW = size.width / s_size.width
        
        let cropRect = NSMakeRect(0, 0, s_size.width, s_size.height)
        var in_rect = NSZeroRect
        
        if ratioH >= ratioW {
            in_rect.size.width = size.width
            in_rect.size.height = s_size.height * ratioW
            in_rect.origin.y = (size.height - in_rect.size.height)/CGFloat(2)
        }
        else {
            in_rect.size.width = ratioH * s_size.width
            in_rect.size.height = size.height
            in_rect.origin.x = (size.width - in_rect.size.width)/CGFloat(2)
        }
        
        t_img.lockFocus()
        
        s_img.draw(in: in_rect, from: cropRect, operation: .copy, fraction: 1.0, respectFlipped: true, hints: [NSImageRep.HintKey.interpolation: NSNumber(integerLiteral: Int(NSImageInterpolation.low.rawValue))])
        
        t_img.unlockFocus()
        
        return t_img
    }

}
